package com.yoo.ons

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.content.pm.ApplicationInfo
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import com.yoo.module_base.extension.isMainProcess
import com.yoo.module_base.utils.LogUtil
import com.tencent.mmkv.MMKV
import com.yoo.chat.kit.IMCenter
import com.yoo.ons.init_model.InitNetworkModel
import io.rong.imlib.RongCoreClient
import io.rong.imlib.model.InitOption
import io.rong.push.RongPushClient
import io.rong.push.pushconfig.PushConfig

class App : Application(), ViewModelStoreOwner {
    private val appViewModelStore by lazy { ViewModelStore() }
    private val appViewModelFactory by lazy { ViewModelProvider.AndroidViewModelFactory.getInstance(this) }
    companion object {
        @JvmStatic @SuppressLint("StaticFieldLeak")
        var context: Context? = null
        @SuppressLint("StaticFieldLeak")
        private var instance: App? = null

        fun getInstance() = instance!!
    }

    override fun onCreate() {
        super.onCreate()
        context = this
        instance = this
        MMKV.initialize(this)
        val isDebuggable = 0 != applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE
        LogUtil.init(isDebuggable)
        if (isMainProcess()){
            sdkInits().forEach{
                it.init(this)
            }
        }
        setIMConfig()
    }


    /**
     * 融云配置
     */
    private fun setIMConfig() {
        val appKey = BuildConfig.IM_TOKEN
        val areaCode = InitOption.AreaCode.NA

        val config: PushConfig = PushConfig.Builder()
            .enableFCM(false)
            .build()
        RongPushClient.setPushConfig(config)
        val initOption = InitOption.Builder()
            .setAreaCode(areaCode)
            .enablePush(true)
            .setNaviServer("nav.us-light-edge.com")
            .build()
        RongCoreClient.setServerInfo("nav.us-light-edge.com", null)
        IMCenter.init(this, appKey, initOption)
    }

    fun getAppViewModelProvider() = ViewModelProvider(this, appViewModelFactory)

    override fun attachBaseContext(base: Context) {
        com.yoo.ons.App.Companion.context = this
        super.attachBaseContext(base)
    }

    private fun sdkInits() = listOf(
        InitNetworkModel()
    )

    override val viewModelStore: ViewModelStore
        get() = appViewModelStore
}